<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="基地名称" prop="baseName">
        <el-input v-model="formData.baseName" placeholder="请输入基地名称" />
      </el-form-item>
      <el-form-item label="基地类型" prop="baseType">
        <el-select v-model="formData.baseType" placeholder="请选择基地类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.DISTRIBUTION_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="地址" prop="areaPath">
        <el-cascader
          v-model="areaPath"
          :options="areaList"
          :props="cascaderProps"
          clearable
          filterable
          placeholder="请选择省/市/区/镇"
          @change="handleAreaChange"
          class="!w-1/1"
        />
        <el-button
          v-if="formData.province"
          type="primary"
          link
          @click="locateByAddress"
          class="ml-2"
        >
          📍 根据地址定位地图
        </el-button>
      </el-form-item>
      <el-form-item label="详细门牌号地址" prop="detailedAddress">
        <el-input v-model="formData.detailedAddress" placeholder="请输入详细门牌号地址" />
      </el-form-item>
      <el-form-item label="地图定位">
        <el-alert title="使用提示" type="info" :closable="false" class="mb-2">
          <template #default>
            <div class="text-sm">
              <p
                >📍 <strong>方式一：搜索地址</strong> -
                在下方输入框中输入详细地址（如：北京市朝阳区xxx街道xxx号）</p
              >
              <p>🖱️ <strong>方式二：点击地图</strong> - 直接在地图上点击选择位置</p>
              <p>💡 搜索建议：请输入完整地址，包含省市区等信息，这样更容易找到准确位置</p>
            </div>
          </template>
        </el-alert>
        <Map
          ref="mapRef"
          :isWrite="true"
          :clickMap="true"
          :center="mapCenter"
          @locate-change="handleLocationChange"
        />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="经度" prop="longitude">
            <el-input v-model="formData.longitude" placeholder="自动获取" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度" prop="latitude">
            <el-input v-model="formData.latitude" placeholder="自动获取" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="服务类型" prop="serveType">
        <el-select v-model="formData.serveType" placeholder="请选择服务类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.DISTRIBUTION_SERVICE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.FARM_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { BaseApi, BaseVO } from '@/api/system/distribution/base'
import { DICT_TYPE, getStrDictOptions, getIntDictOptions } from '@/utils/dict'
import * as AreaApi from '@/api/system/area'
import Map from '@/components/Map/index.vue'

/** 配送基地 表单 */
defineOptions({ name: 'BaseForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  baseName: undefined,
  baseType: undefined,
  province: undefined as string | undefined,
  city: undefined as string | undefined,
  district: undefined as string | undefined,
  town: undefined as string | undefined,
  detailedAddress: undefined,
  longitude: undefined as number | undefined,
  latitude: undefined as number | undefined,
  serveType: undefined,
  status: undefined as number | undefined
})
const areaList = ref<any[]>([]) // 地区列表
const areaPath = ref<number[]>([]) // 地区选择路径
const mapRef = ref() // 地图组件引用
const mapCenter = ref('') // 地图中心点（经度,纬度）
const cascaderProps = {
  children: 'children',
  label: 'name',
  value: 'id',
  isLeaf: 'leaf',
  emitPath: true // 返回完整路径数组
}
const formRules = reactive({
  baseName: [{ required: true, message: '基地名称不能为空', trigger: 'blur' }],
  baseType: [{ required: true, message: '基地类型不能为空', trigger: 'change' }],
  province: [{ required: true, message: '省份不能为空', trigger: 'blur' }],
  city: [{ required: true, message: '城市不能为空', trigger: 'blur' }],
  district: [{ required: true, message: '区县不能为空', trigger: 'blur' }],
  detailedAddress: [{ required: true, message: '详细门牌号地址不能为空', trigger: 'blur' }],
  longitude: [{ required: true, message: '经度不能为空', trigger: 'blur' }],
  latitude: [{ required: true, message: '纬度不能为空', trigger: 'blur' }],
  serveType: [{ required: true, message: '服务类型不能为空', trigger: 'change' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 加载地区列表
  if (areaList.value.length === 0) {
    areaList.value = await AreaApi.getAreaTree()
  }

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BaseApi.getBase(id)

      // 如果有地区信息，需要构建地区路径用于显示
      if (formData.value.province) {
        buildAreaPath()
      }
      // 如果有经纬度，设置地图中心点
      if (formData.value.longitude && formData.value.latitude) {
        mapCenter.value = `${formData.value.longitude},${formData.value.latitude}`
        // 延迟调用地图定位，确保地图组件已渲染
        nextTick(() => {
          mapRef.value?.regeoCode(mapCenter.value)
        })
      }
    } finally {
      formLoading.value = false
    }
  } else {
    // 新增时，设置默认值
    formData.value.status = 1 // 默认开启
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BaseVO
    if (formType.value === 'create') {
      await BaseApi.createBase(data)
      message.success(t('common.createSuccess'))
    } else {
      await BaseApi.updateBase(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    baseName: undefined,
    baseType: undefined,
    province: undefined as string | undefined,
    city: undefined as string | undefined,
    district: undefined as string | undefined,
    town: undefined as string | undefined,
    detailedAddress: undefined,
    longitude: undefined as number | undefined,
    latitude: undefined as number | undefined,
    serveType: undefined,
    status: undefined as number | undefined
  }
  areaPath.value = [] as number[] // 清空地区路径
  mapCenter.value = '' // 清空地图中心点
  formRef.value?.resetFields()
}

/** 地区选择改变 */
const handleAreaChange = (value: any[]) => {
  if (!value || value.length === 0) {
    // 清空地区信息
    formData.value.province = undefined
    formData.value.city = undefined
    formData.value.district = undefined
    formData.value.town = undefined
    return
  }

  // 根据选择的路径，从地区树中找到对应的名称
  const names = getAreaNames(value)

  // 根据选择的层级，分别赋值
  formData.value.province = names[0] || undefined
  formData.value.city = names[1] || undefined
  formData.value.district = names[2] || undefined
  formData.value.town = names[3] || undefined
}

/** 根据ID路径获取地区名称 */
const getAreaNames = (idPath: number[]): string[] => {
  const names: string[] = []
  let currentList = areaList.value

  for (const id of idPath) {
    const node = currentList.find((item: any) => item.id === id)
    if (node) {
      names.push(node.name)
      currentList = node.children || []
    } else {
      break
    }
  }

  return names
}

/** 构建地区路径（用于编辑时回显） */
const buildAreaPath = () => {
  const { province, city, district, town } = formData.value
  if (!province) {
    areaPath.value = []
    return
  }

  const path: number[] = []
  let currentList = areaList.value

  // 查找省份
  const provinceNode = currentList.find((item: any) => item.name === province)
  if (provinceNode) {
    path.push(provinceNode.id)
    currentList = provinceNode.children || []

    // 查找城市
    if (city) {
      const cityNode = currentList.find((item: any) => item.name === city)
      if (cityNode) {
        path.push(cityNode.id)
        currentList = cityNode.children || []

        // 查找区县
        if (district) {
          const districtNode = currentList.find((item: any) => item.name === district)
          if (districtNode) {
            path.push(districtNode.id)
            currentList = districtNode.children || []

            // 查找乡镇
            if (town) {
              const townNode = currentList.find((item: any) => item.name === town)
              if (townNode) {
                path.push(townNode.id)
              }
            }
          }
        }
      }
    }
  }

  areaPath.value = path
}

/** 地图位置改变事件 */
const handleLocationChange = (lnglat: string[]) => {
  if (lnglat && lnglat.length === 2) {
    formData.value.longitude = parseFloat(lnglat[0])
    formData.value.latitude = parseFloat(lnglat[1])
  }
}

/** 根据地址定位地图 */
const locateByAddress = () => {
  // 构建完整地址
  const addressParts = [
    formData.value.province,
    formData.value.city,
    formData.value.district,
    formData.value.town,
    formData.value.detailedAddress
  ].filter(Boolean) // 过滤掉空值

  const fullAddress = addressParts.join('')

  if (!fullAddress) {
    message.warning('请先选择地址信息')
    return
  }

  message.info(`请在地图搜索框中输入：${fullAddress}`)
}
</script>
